
package com.ucpaas.sms.action.atuoAndBalckTemplate;

import com.jsmsframework.audit.dto.JsmsBalckTemplateDTO;
import com.jsmsframework.audit.entity.JsmsAutoBlackTemplate;
import com.jsmsframework.audit.service.JsmsAutoBlackTemplateService;
import com.jsmsframework.common.constant.SysConstant;
import com.jsmsframework.common.dto.JsmsPage;

import com.jsmsframework.common.dto.R;
import com.jsmsframework.common.dto.ResultVO;
import com.jsmsframework.common.entity.JsmsParam;
import com.jsmsframework.common.enums.balckAndWhiteTemplate.BalckTemplateState;
import com.jsmsframework.common.enums.balckAndWhiteTemplate.TemplateLevel;
import com.jsmsframework.common.service.JsmsParamService;
import com.jsmsframework.common.util.BeanUtil;
import com.jsmsframework.common.util.JsonUtil;
import com.jsmsframework.user.audit.service.JsmsUserBalckTemplateService;
import com.jsmsframework.user.entity.JsmsUser;
import com.jsmsframework.user.service.JsmsAccountService;
import com.jsmsframework.user.service.JsmsUserService;
import com.ucpaas.sms.action.BaseAction;

import com.ucpaas.sms.constant.LogConstant;
import com.ucpaas.sms.enums.LogEnum;
import com.ucpaas.sms.model.Excel;
import com.ucpaas.sms.service.LogService;
import com.ucpaas.sms.util.CommonUtil;

import com.ucpaas.sms.util.ConfigUtils;
import com.ucpaas.sms.util.UpaasHtmlUtils;
import com.ucpaas.sms.util.file.ExcelUtils;
import com.ucpaas.sms.util.file.FileUtils;
import com.ucpaas.sms.util.rest.utils.DateUtil;
import com.ucpaas.sms.util.web.AuthorityUtils;
import com.ucpaas.sms.util.web.StrutsUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

import static com.ucpaas.sms.action.atuoAndBalckTemplate.AutoTemplateAction.replaceBlank;

/**
 * 黑模板管理
 */
@Controller
@Scope("prototype")
@Results({
		@Result(name = "balcktemplateQuery", location = "/WEB-INF/content/balckAndWhiteTemplate/balck/list.jsp"),
		@Result(name = "generalTemplateAdd", location = "/WEB-INF/content/balckAndWhiteTemplate/balck/addGeneral.jsp"),
		@Result(name = "userTemplateAdd", location = "/WEB-INF/content/balckAndWhiteTemplate/balck/addUser.jsp")})
public class BalckTemplateAction extends BaseAction {
	private static final long serialVersionUID = 247987432825275374L;

	private static Logger logger = LoggerFactory.getLogger(BalckTemplateAction.class);

	@Autowired
	private LogService logService;

	@Autowired
	private JsmsAutoBlackTemplateService jsmsAutoBlackTemplateService;

	@Autowired
	private JsmsAccountService jsmsAccountService;

	@Autowired
	private JsmsUserBalckTemplateService jsmsUserBalckTemplateService;

	@Autowired
	private JsmsUserService jsmsUserService;
	@Autowired
    private JsmsParamService jsmsParamService;

	private File upload;
	private String uploadFileName;
	private String uploadContentType;

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}



	/**
	 * 黑模板管理--
	 *
	 * @return 返回页面
	 */
	@Action("/balckTemplate/balckTemplate/query")
	public String balckTemplateQuery() {
		Map<String, String> params = StrutsUtils.getFormData();
		Map<String, Object> objectMap = new HashMap<>();

		Object obj = new Object();
		// 模板状态
		obj = params.get("state");
		if (obj != null) {
			objectMap.put("state", obj);
		}
		// 模板属性
		obj = params.get("smsType");
		if (obj != null) {
			objectMap.put("smsType", obj);
		}
		// 模板类型
		obj = params.get("templateType");
		if (obj != null) {
			objectMap.put("templateType", obj);
		}
		// 模版ID
		obj = params.get("templateId");
		if (obj != null) {
			objectMap.put("templateId", obj);
		}
		// 短信签名
		obj = params.get("sign");
		if (obj != null) {
			objectMap.put("sign", obj);
		}
		// 模版内容
		obj = params.get("content");
		if (obj != null) {
			objectMap.put("content", obj);
		}
		// 用户帐号
		obj = params.get("clientId");
		if (obj != null) {
			objectMap.put("clientId", obj);
		}
		// 创建人
		obj = params.get("userName");
		if (obj != null) {
			objectMap.put("userName", obj);
		}
		// 模板级别
		obj = params.get("templateLevel");
		if (obj != null) {
			objectMap.put("templateLevel", obj);
		}

		// 更新时间：开始时间
		DateTime dt = DateTime.now();
		String startTime = Objects.toString(params.get("startTime"), "");
		String endTime = Objects.toString(params.get("endTime"), "");
		if (StringUtils.isNotBlank(startTime)) {
			objectMap.put("startTime", startTime);
		}else{

			startTime = DateUtil.dateToStr(DateUtil.getDateFromToday(-30),DateUtil.YMR_SLASH)+" 00:00:00";
			objectMap.put("startTime", startTime);
		}

		// 更新时间：结束时间
		if (StringUtils.isNotBlank(endTime)) {
			objectMap.put("endTime", endTime);
		}else {
			endTime=DateUtil.dateToStr(DateUtil.getDateFromToday(0),DateUtil.YMR_SLASH)+" 23:59:59";
			//endTime = dt.plusMinutes(1).toString("yyyy-MM-dd HH:mm:ss");
			objectMap.put("endTime", endTime);
		}

		//匹配次数
        obj = params.get("minNum");
        if (obj != null) {
            objectMap.put("minNum", obj);
        }
        obj = params.get("maxNum");
        if (obj != null) {
            objectMap.put("maxNum", obj);
        }


		// 用于页面回显"更新时间"
		StrutsUtils.setAttribute("startTime", startTime);
		StrutsUtils.setAttribute("endTime", endTime);
		StrutsUtils.setAttribute("clientIdHidden", Objects.toString(params.get("clientId"), ""));

		JsmsPage<JsmsAutoBlackTemplate> jsmsPage = CommonUtil.initJsmsPage(params);
		jsmsPage.setParams(objectMap);
		jsmsPage.setOrderByClause("a.update_time DESC");

		jpage = jsmsUserBalckTemplateService.findListOfBalckTemplate(jsmsPage);


		return "balcktemplateQuery";
	}


	@Action("/balckTemplate/generalTemplate/add")
	public String generalTemplateAdd() {
		Map<String, String> params = StrutsUtils.getFormData();
		if(params.get("templateId")!=null){
			Integer templateId=Integer.valueOf(params.get("templateId"));
			JsmsAutoBlackTemplate balck=jsmsAutoBlackTemplateService.getByTemplateId(templateId);
			Map<String,Object> data1=new HashedMap();

			data1=BeanUtil.beanToMap(balck,false);
			data1.put("content", UpaasHtmlUtils.Html2Text(balck.getContent()==null?"":balck.getContent().trim()));

			data=data1;
		}

		return "generalTemplateAdd";
	}


	@Action("/balckTemplate/userTemplateAdd/add")
	public String userTemplateAdd() {
		Map<String, String> params = StrutsUtils.getFormData();
		if(params.get("templateId")!=null){
			Integer templateId=Integer.valueOf(params.get("templateId")).intValue();
			JsmsAutoBlackTemplate balck=jsmsAutoBlackTemplateService.getByTemplateId(templateId);
			Map<String,Object> data1=new HashedMap();
			data1=BeanUtil.beanToMap(balck,false);
			data1.put("content",UpaasHtmlUtils.Html2Text(balck.getContent()==null?"":balck.getContent().trim()));

			data=data1;
		}

		return "userTemplateAdd";
	}

	/**
	 * 新增or编辑智能模板审核
	 */
	@Action("/balckTemplate/template/save")
	public void balckTemplateSave(){
		Map<String, String> params = StrutsUtils.getFormData();

		boolean isMod = false;
		JsmsBalckTemplateDTO template = new JsmsBalckTemplateDTO();

		// 模版ID
		Object obj = params.get("templateId");
		if (obj != null) {
			isMod = true;
			template.setTemplateId(Integer.parseInt(obj.toString()));
		}
        // 模版ID
        obj = params.get("templateLevel");
        if (obj != null) {
            template.setTemplateLevel(Integer.parseInt(obj.toString()));
        }

		R r =this.checkOverNum(template);
        if(Objects.equals(r.getCode(),SysConstant.FAIL_CODE)){
			StrutsUtils.renderJson(r);
		}else {
			// 用户帐号
			obj = params.get("clientId");
			if (obj != null) {
				template.setClientId(obj.toString());
			}else if(obj==null && Objects.equals(template.getTemplateLevel(), TemplateLevel.全局级别.getValue())) {
				template.setClientId(SysConstant.ALL);
			}else  if(isMod){
                obj = params.get("clientId1");
                if (obj != null) {
                    template.setClientId(obj.toString());
                }
            }

			// 模版类型
			obj = params.get("templateType");
			if (obj != null) {
				template.setTemplateType(Integer.parseInt(obj.toString()));
			}

			// 短信类型
			obj = params.get("smsType");
			if (obj != null) {
				template.setSmsType(Integer.parseInt(obj.toString()));
			}/*else{
			StrutsUtils.renderJson(R.error("请选择短信类型"));
			return;
		}*/

			// 模版内容
			obj = params.get("content");
			if (obj != null) {
				template.setContent(obj.toString());
			}
			//模板状态
			obj = params.get("state");

			if (obj != null) {
				template.setState(Integer.valueOf(obj.toString()));
			}
			// 短信签名
			obj = params.get("sign");
			if (obj != null) {
				template.setSign(obj.toString());
			}else {
				template.setSign(null);
			}
			//删除标志
			boolean isSureDel = false;
			obj = params.get("isSureDel");
			if(obj != null){
				isSureDel = Boolean.parseBoolean(String.valueOf(obj));
			}
			template.setSureDel(isSureDel);

			if ((StringUtils.isBlank(template.getClientId())|| jsmsAccountService.getByClientId(template.getClientId()) == null) && Objects.equals(template.getTemplateLevel(), TemplateLevel.用户级别.getValue())){
				StrutsUtils.renderJson(R.error("用户账号不存在"));
			}else {
				if (isMod) {
					logService.add(LogConstant.LogType.update, LogEnum.智能模板管理.getValue(), "智能模板管理-黑模板管理：编辑模版", params,JsonUtil.toJson(template),"操作人："+AuthorityUtils.getLoginUserId());
					template.setLatelyMatchAmount(0);
					template.setLatelyMatchDate(null);
					template.setMatchAmount(0);
					r = jsmsAutoBlackTemplateService.editBalckTemplate(template);
				} else {
					logService.add(LogConstant.LogType.add, LogEnum.智能模板管理.getValue(), "智能模板管理-黑模板管理：添加模版", params, JsonUtil.toJson(template),"操作人："+AuthorityUtils.getLoginUserId());
					if(template.getState()==null) {
						template.setState(BalckTemplateState.启用.getValue());
					}
					// 创建人
					template.setUserId(AuthorityUtils.getLoginUserId().toString());
					r = jsmsAutoBlackTemplateService.addBalackTemplate(template);
				}

				StrutsUtils.renderJson(r);
			}

		}


	}


	/**
	 * 查询是否超标添加全局模板
	 * @param template
	 * @return
	 */
	private R checkOverNum(JsmsBalckTemplateDTO template){
		//校验是否超标添加全局模板
		if(template.getTemplateId()==null && Objects.equals(template.getTemplateLevel(),TemplateLevel.全局级别.getValue())){
			List<JsmsParam> paramKey = jsmsParamService.getByParamKey(SysConstant.GLOBAL_TEMPLATE_NUMBER);
			if(paramKey != null && paramKey.size()>0){
				JsmsParam overparam = paramKey.get(0);
				BigDecimal overNum=new BigDecimal(overparam.getParamValue());
				Map<String,Object> param=new HashedMap();
				param.put("templateLevel",TemplateLevel.全局级别.getValue());
				param.put("state",BalckTemplateState.启用.getValue());
				int count=jsmsAutoBlackTemplateService.count(param);
				if(BigDecimal.valueOf(count).compareTo(overNum)!=-1){
					return	R.error("通用模板已达到最高限制数！");
				}
			}else{
				return  R.error("无全局模板参数");
			}
		}
		return  R.ok("通用模板可添加");

	}




	@Action("/balckTemplate/template/updateState")
	public void updateState() {
		Map<String, String> params = StrutsUtils.getFormData();

		if(params.get("templateId")==null){
			StrutsUtils.renderJson(R.error("模板ID不能为空"));
		}else {
			if(params.get("state")==null){
				StrutsUtils.renderJson(R.error("模板改变状态不能为空"));
			}else {
				try{
				int templateId=Integer.valueOf(params.get("templateId")).intValue();
				int state=Integer.valueOf(params.get("state")).intValue();
				JsmsAutoBlackTemplate balckTemplate=jsmsAutoBlackTemplateService.getByTemplateId(templateId);
				if(balckTemplate!=null ){
					if(Objects.equals(state,BalckTemplateState.启用.getValue())){
						JsmsBalckTemplateDTO dto=new JsmsBalckTemplateDTO();
						BeanUtil.copyProperties(balckTemplate,dto);
						dto.setTemplateId(null);
						R r1 =this.checkOverNum(dto);
						if(Objects.equals(r1.getCode(),SysConstant.FAIL_CODE)){
							StrutsUtils.renderJson(r1);
							return;
						}
					}
				}else {
					StrutsUtils.renderJson(R.error("参数非法！"));
				}


				if(BalckTemplateState.getDescByValue(Integer.valueOf(params.get("state")))==null){
					StrutsUtils.renderJson(R.error("参数非法！"));
				}
				R r=jsmsAutoBlackTemplateService.updateState4BalckTemplate(templateId,state);
				logService.add(LogConstant.LogType.update, LogEnum.智能模板管理.getValue(), "智能模板管理-黑模板管理：修改状态", params,JsonUtil.toJson(balckTemplate),"操作人："+AuthorityUtils.getLoginUserId());
				StrutsUtils.renderJson(r);
				}catch (NumberFormatException e){
					StrutsUtils.renderJson(R.error("非法参数！"));
				}
			}


		}

	}

	@Action("/balckTemplate/template/delTemplate")
	public void delTemplate() {
		Map<String, String> params = StrutsUtils.getFormData();

		if(params.get("templateId")==null){
			StrutsUtils.renderJson(R.error("模板ID不能为空"));
		}else {

			try{
				int templateId=Integer.valueOf(params.get("templateId"));
				R r=jsmsAutoBlackTemplateService.delBalckTemplate(templateId);
				logService.add(LogConstant.LogType.delete, LogEnum.智能模板管理.getValue(), "智能模板管理-黑模板管理：删除操作", params,"黑模板ID:"+templateId,"操作人："+AuthorityUtils.getLoginUserId());
				StrutsUtils.renderJson(r);
			}catch (NumberFormatException e){
				StrutsUtils.renderJson(R.error("非法模板ID"));
			}



		}

	}

	/**
	 * 下载批量添加用户黑模板Excel
	 */
	@Action("/balckTemplate/downloadExcelTemplate")
	public void downloadExcelTemplate() {
		String path = StrutsUtils.getRequest().getServletContext().getRealPath("/templateFile/批量添加黑模板.xls");
		FileUtils.download(path);
	}


	/**
	 * 黑模板管理--> 导出
	 *
	 * @return 返回页面
	 */
	@Action("/balckTemplate/template/export")
	public void autoTemplateExport() {
		Map<String, String> params = StrutsUtils.getFormData();

		Object obj = new Object();
//		objectMap.putAll(params);


		// 更新时间：开始时间
		if (StringUtils.isBlank(params.get("startTime"))) {
			String startTime = DateUtil.dateToStr(DateUtil.getDateFromToday(-30),DateUtil.YMR_SLASH)+" 00:00:00";
			params.put("startTime", startTime);
		}
		// 更新时间：结束时间
		if (StringUtils.isBlank(params.get("endTime"))) {
			DateTime dt = DateTime.now();
			String endTime = dt.toString("yyyy-MM-dd HH:mm:ss");
			params.put("endTime", endTime);
		}

		StringBuffer filePath = new StringBuffer(ConfigUtils.save_path);
		if(!ConfigUtils.save_path.endsWith("/")){
			filePath.append("/");
		}
		filePath.append("黑模板记录")
				.append(".xls")
				.append("$$$")
				.append(UUID.randomUUID());
		Excel excel = new Excel();
		excel.setFilePath(filePath.toString());
		excel.setTitle("黑模板记录");

		StringBuffer buffer = new StringBuffer();
		buffer.append("查询条件：");
		String condition = null;
		condition = params.get("_state");
		if (StringUtils.isNoneBlank(condition)) {
			buffer.append("  模板状态：");
			buffer.append(condition);
			buffer.append(";");
		}

		condition = params.get("_smsType");
		if (StringUtils.isNoneBlank(condition)) {
			buffer.append("  模板属性：");
			buffer.append(condition);
			buffer.append(";");
		}
		condition = params.get("_");
		if (StringUtils.isNoneBlank(condition)) {
			buffer.append("  模板属性：");
			buffer.append(condition);
			buffer.append(";");
		}
		condition = params.get("_templateType");
		if (StringUtils.isNoneBlank(condition)) {
			buffer.append("  模板类型：");
			buffer.append(condition);
			buffer.append(";");
		}
		condition = params.get("templateId");
		if (StringUtils.isNoneBlank(condition)) {
			buffer.append("  模板ID：");
			buffer.append(condition);
			buffer.append(";");
		}
		condition = params.get("sign");
		if (StringUtils.isNoneBlank(condition)) {
			buffer.append("  签名：");
			buffer.append(condition);
			buffer.append(";");
		}
		condition = params.get("content");
		if (StringUtils.isNoneBlank(condition)) {
			buffer.append("  模板内容：");
			buffer.append(condition);
			buffer.append(";");
		}
		condition = params.get("clientId");
		if (StringUtils.isNoneBlank(condition)) {
			buffer.append("  用户账号：");
			buffer.append(condition);
			buffer.append(";");
		}

		condition = params.get("userName");
		if (StringUtils.isNoneBlank(condition)) {
			buffer.append("  创建者：");
			buffer.append(condition);
			buffer.append(";");
		}

		condition = params.get("startTime");
		if (StringUtils.isNoneBlank(condition)) {
			buffer.append("  更新时间(开始)：");
			buffer.append(condition);
			buffer.append(";");
		}
		condition = params.get("endTime");
		if (StringUtils.isNoneBlank(condition)) {
			buffer.append("  更新时间(结束)：");
			buffer.append(condition);
			buffer.append(";");
		}
		condition = params.get("minNum");
		if (StringUtils.isNoneBlank(condition)) {
			buffer.append("  匹配次数(区间开始)：");
			buffer.append(condition);
			buffer.append(";");
		}
		condition = params.get("maxNum");
		if (StringUtils.isNoneBlank(condition)) {
			buffer.append("  匹配次数(区间结束)：");
			buffer.append(condition);
			buffer.append(";");
		}
		excel.addRemark(buffer.toString());
		excel.addHeader(20, "模板级别", "templateLevelStr");
		excel.addHeader(20, "模板ID", "templateId");
		excel.addHeader(20, "用户账号", "clientId");
		excel.addHeader(20, "模板属性", "smsTypeStr");
		excel.addHeader(20, "模板类型", "templateTypeStr");
		excel.addHeader(20, "模板内容", "content");
		excel.addHeader(20, "短信签名", "sign");
		excel.addHeader(20, "创建者", "userName");
		excel.addHeader(20, "更新时间", "updateTimeStr");
		excel.addHeader(20, "模板状态", "stateStr");
		excel.addHeader(20, "匹配次数", "matchAmount");
		excel.addHeader(20, "最近匹配数", "latelyMatchAmount");
		excel.addHeader(20, "最近匹配日期", "latelyMatchDateStr");

		JsmsPage<JsmsBalckTemplateDTO> jsmsPage = CommonUtil.initJsmsPage(params);
		jsmsPage.setOrderByClause("a.update_time DESC");
		jsmsPage.setRows(Integer.valueOf(ConfigUtils.max_export_excel_num) + 1);

		ResultVO resultVO = null;
		try {
			jsmsAutoBlackTemplateService.queryList(jsmsPage);
			List<JsmsBalckTemplateDTO> list = new ArrayList<>();
			List result = new ArrayList();
			for (Object temp : jsmsPage.getData()) {
				JsmsBalckTemplateDTO jsmsBalckTemplateDTO = new JsmsBalckTemplateDTO();
				BeanUtils.copyProperties(temp , jsmsBalckTemplateDTO);

				JsmsUser jsmsUser1 = jsmsUserService.getById(jsmsBalckTemplateDTO.getUserId());
				if(jsmsUser1 != null){
					jsmsBalckTemplateDTO.setUserName(jsmsUser1.getRealname());
				}
				if(jsmsBalckTemplateDTO.getSign()==null){
					jsmsBalckTemplateDTO.setSign("*");
				}
				Map<String, String> describe = org.apache.commons.beanutils.BeanUtils.describe(jsmsBalckTemplateDTO);
				result.add(describe);
			}

			if (result == null || result.size() <= 0){
				resultVO = ResultVO.failure("没有数据！先不导出了  ^_^");
			}else if (result.size() > Integer.valueOf(ConfigUtils.max_export_excel_num)){
				resultVO =  ResultVO.failure("数据量超过"+ConfigUtils.max_export_excel_num+"，请缩小范围后再导出吧  ^_^");
			}

            /* 合计需要添加合计方法
            page = (JsmsPage) this.getClass().getMethod(queryMethod + "Total",page.getClass()).invoke(this, page);
            result.add(BeanUtils.describe(page.getTotalOtherData().get("totalLine")));*/
			excel.setDataList(result);
			if (ExcelUtils.exportExcel(excel)) {
				resultVO = ResultVO.successDefault();
				resultVO.setMsg("报表生成成功");
				resultVO.setData(excel.getFilePath());
			}
		} catch (Exception e) {
//			logg.error("生成报表失败", e);
			e.printStackTrace();
		}
		StrutsUtils.renderJson(resultVO);
	}

	/**
	 * 批量添加黑模板
	 */
	@Action("/balckTemplate/addBalckTemplateBatch")
	public void importExcel() {
		R r = jsmsUserBalckTemplateService.addBalckTemplateBatch(upload, uploadContentType, String.valueOf(AuthorityUtils.getLoginUserId()), ConfigUtils.save_path);
		StrutsUtils.renderJson(r);
	}

	@Action("/balckTemplate/exportImportResult")
	public void exportError(){
		String filePath = ConfigUtils.save_path +"/import"+ "/批量添加黑模板结果-userid-" + AuthorityUtils.getLoginUserId()+".xls";
		File file = new File(filePath);
		if(file.exists()){
			FileUtils.download(filePath);
		}else{
			StrutsUtils.renderText("文件过期、不存在或者已经被管理员删除");
		}
	}
}
